/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */
export var mostCommonWord = function (paragraph, banned) {
  const wordCount = {}

  let words = paragraph.toLocaleLowerCase().split(/\W+/)

  for (let i = 0; i < words.length; i++) {
    const word = words[i]
    if (banned.includes(word)) continue
    wordCount[word] = (wordCount[word] || 0) + 1
  }

  /*
    * // 这方案更简短，但会慢点
    return Object.keys(wordCount).sort((a,b)=>wordCount[b] - wordCount[a])[0];
  */

  let ans = ''
  let max = 0
  const newWords = Object.keys(wordCount)
  for (let i = 0; i < newWords.length; i++) {
    const word = newWords[i]
    if (wordCount[word] > max) {
      max = wordCount[word]
      ans = word
    }
  }
  return ans
}

/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */
export var mostCommonWord2 = function (paragraph, banned) {
  const wordCount = {}

  paragraph
    .toLocaleLowerCase()
    .split(/\W+/)
    .forEach(n => {
      if (banned.includes(n)) return
      wordCount[n] = (wordCount[n] || 0) + 1
    })

  let ans = ''
  let max = 0
  const newWords = Object.keys(wordCount)
  for (let i = 0; i < newWords.length; i++) {
    const word = newWords[i]
    if (wordCount[word] > max) {
      max = wordCount[word]
      ans = word
    }
  }
  return ans
}
